<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分类数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container" style="margin-bottom: 10px" v-if="selectCategory">
          <el-alert :title="selectCategory" type="info" close-text="取消选中" show-icon @close="cancelSelect" />
        </div>
        <div class="head-container">
          <el-input
            v-model="categoryName"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="categoryOptions"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="categoryTreeRef"
            node-key="id"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--流程数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:deployment:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-s-cooperation"
              size="mini"
              @click="handleOpenDraft"
            >草稿箱</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-alert title="流程设计说明" type="success">
          <template slot='title'>
            <span>流程设计说明:</span>
            <div>1、XML文件中的流程定义id属性用作流程定义的key参数。</div>
            <div>2、XML文件中的流程定义name属性用作流程定义的name参数。如果未给定name属性，会使用id作为name。</div>
            <div>3、当每个唯一key的流程第一次部署时，指定版本为1。对其后所有使用相同key的流程定义，部署时版本会在该key当前已部署的最高版本号基础上加1。key参数用于区分流程定义。</div>
            <div>4、id参数设置为{processDefinitionKey}:{processDefinitionVersion}:{generated-id}，其中generated-id是一个唯一数字，用以保证在集群环境下，流程定义缓存中，流程id的唯一性。</div>
          </template>
        </el-alert>
        <el-table v-loading="loading" fit :data="definitionList" border size="mini" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="流程编码" align="center" prop="id" :show-overflow-tooltip="true"/>
          <el-table-column label="流程名称" align="center" width="140" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-button type="text" @click="handleReadImage(scope.row.deploymentId)">
                <span>{{ scope.row.name }}</span>
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="业务表单" align="center" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-button v-if="scope.row.formId" type="text" @click="handleForm(scope.row.formId)">
                <span>{{ scope.row.formName }}</span>
              </el-button>
              <label v-else>暂无表单</label>
            </template>
          </el-table-column>
          <el-table-column label="版本" width="80" align="center">
            <template slot-scope="scope">
              <el-tag effect="plain" size="small">v{{ scope.row.version }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="80" align="center">
            <template slot-scope="scope">
              <el-tag effect="plain" size="small" v-if="scope.row.suspensionState === 1">激活</el-tag>
              <el-tag type="danger" effect="plain" size="small" v-if="scope.row.suspensionState === 2">挂起</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="部署时间" align="center" prop="deploymentTime" width="160"/>
          <el-table-column label="操作" width="100" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-tooltip content="设计" placement="top">
                <el-button @click="handleUpdate(scope.row)" icon="el-icon-edit-outline" type="text" size="small"/>
              </el-tooltip>
<!--              <el-tooltip content="配置主表单" placement="top" v-if="scope.row.formId == null">-->
<!--                <el-button @click="handleAddForm(scope.row)" icon="el-icon-document-add" type="text" size="small" />-->
<!--              </el-tooltip>-->
              <el-tooltip content="挂起" placement="top" v-if="scope.row.suspensionState === 1">
                <el-button @click="handleUpdateSuspensionState(scope.row)" icon="el-icon-video-pause" type="text" size="small" />
              </el-tooltip>
              <el-tooltip content="激活" placement="top" v-if="scope.row.suspensionState === 2">
                <el-button @click="handleUpdateSuspensionState(scope.row)" icon="el-icon-video-play" type="text" size="small" style="color: #f56c6c" />
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button @click="handleDelete(scope.row)" icon="el-icon-delete" type="text" size="small" v-hasPermi="['system:deployment:remove']" style="color: #f56c6c"/>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 流程图 -->
    <el-dialog :title="readImage.title" :visible.sync="readImage.open" width="70%" append-to-body>
      <bpmn-viewer :flowData="flowData"/>
    </el-dialog>

    <!--表单配置详情-->
    <el-dialog :visible.sync="formConfOpen" width="50%" append-to-body>
      <div slot="title">
        <span class="inner">{{formTitleConf.formName}}</span>
        <dict-tag class="inner" :options="dict.type.form_type" :value="formTitleConf.formType"/>
      </div>
      <div class="test-form">
        <v-form-render  v-if="renderForm" :form-data="formData" ref="vFormRef"/>
        <component v-else :is="formCompName" ref="vFormRef"></component>
      </div>
    </el-dialog>

    <!--挂载表单-->
    <el-dialog title="流程主表单" :visible.sync="formDeployOpen" width="70%" append-to-body>
      <el-row :gutter="24">
        <el-col :span="10" :xs="24">
          <el-table
            ref="singleTable"
            :data="formList"
            border
            highlight-current-row
            @current-change="handleCurrentChange"
            style="width: 100%">
            <el-table-column label="表单编号" align="center" prop="formId" />
            <el-table-column label="表单名称" align="center" prop="formName" />
            <el-table-column label="表单类型" align="center" prop="formType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.form_type" :value="scope.row.formType"/>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleDesign(scope.row)">确定</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            small
            layout="prev, pager, next"
            v-show="formTotal>0"
            :total="formTotal"
            :page.sync="formQueryParams.pageNum"
            :limit.sync="formQueryParams.pageSize"
            @pagination="ListFormDeploy"
          />
        </el-col>
        <el-col :span="14" :xs="24">
          <div class="test-form">
            <v-form-render  v-if="renderForm" :form-data="formData" ref="vFormCurrentRowRef"/>
            <component v-else :is="formCompName" ref="vFormCurrentRowRef"></component>
          </div>
        </el-col>
      </el-row>
    </el-dialog>


    <!--草稿信息-->
    <el-dialog
      title="草稿信息"
      size="45%"
      :visible.sync="draftOpen"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      append-to-body
    >
      <el-table v-loading="draftLoading" :data="flowDraftList">
        <el-table-column label="主键" align="center" prop="id" />
        <el-table-column label="草稿名称" align="center" prop="name" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-promotion"
              @click="handleUseDraft(scope.row)"
            >使用</el-button>
            <el-button
              size="mini"
              type="text"
              style="color: #f56c6c"
              icon="el-icon-delete"
              @click="handleDeleteDraft(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        layout="prev, pager, next"
        v-show="draftTotal>0"
        :total="draftTotal"
        :page.sync="draftQueryParams.pageNum"
        :limit.sync="draftQueryParams.pageSize"
        @pagination="getDraftList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  listDefinition,
  updateState,
  delDeployment,
  exportDeployment,
  flowXmlAndNode
} from "@/api/flowable/definition";
import { categoryTree } from "@/api/flowable/category";
import { getForm, addDeployForm ,listForm } from "@/api/flowable/form";
import {delDraft, listDraft} from "@/api/flowable/draft";
import BpmnViewer from '@/components/Process/viewer';
import Model from './model';

export default {
  name: "Definition",
  dicts: ['form_type'],
  components: {
    BpmnViewer,
    Model
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      dialogVisible: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 流程定义表格数据
      definitionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      formConfOpen: false,
      formTitleConf: {},
      formDeployOpen: false,
      formList: [],
      formTotal:0,
      formData: {}, // 默认表单数据
      readImage:{
        open: false,
        src: "",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        category: null,
      },
      formQueryParams:{
        pageNum: 1,
        pageSize: 10,
      },
      deployId: '',
      currentRow: null,
      // xml
      flowData: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 流程分类
      selectCategory: null,
      categoryName: null,
      categoryOptions: null,
      renderForm: true, // 是否渲染在线表单
      formCompName: '', // 路由表单组件名称

      // 草稿信息
      draftOpen: false,
      draftLoading: true, // 是否显示遮罩层
      flowDraftList: [], // 草稿内容
      draftTotal: 0,
      draftQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
    };
  },
  created() {
    this.getList();
    this.getCategoryTree();
  },
  watch:{
    categoryName(val){
        this.$refs["categoryTreeRef"].filter(val);
    }
  },
  activated() {
    const time = this.$route.query.t;
    if (time != null) {
      this.getList();
      this.getCategoryTree();
    }
  },
  methods: {
    /** 查询流程定义列表 */
    getList() {
      this.loading = true;
      listDefinition(this.queryParams).then(response => {
        this.definitionList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 查询分类下拉树结构 */
    getCategoryTree() {
      categoryTree().then(response => {
        this.categoryOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (data.parentId === 0) {
        this.$modal.msgWarning("父级节点只做分类展示,请选择子节点进行查询!");
      } else {
        this.queryParams.category = data.id;
        this.selectCategory = data.label;
        this.handleQuery();
      }
    },
    // 取消选中
    cancelSelect() {
      this.selectCategory = null;
      this.queryParams.category = null;
      this.$refs.categoryTreeRef.setCurrentKey(null);
      this.handleQuery();
    },
    handleClose(done) {
      this.$confirm('确定要关闭吗？关闭未保存的修改都会丢失？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done();
      }).catch(() => {});
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.category = null;
      this.$refs.categoryTreeRef.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deploymentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增流程设计,先选择主表单 */
    handleAdd(){
      this.ListFormDeploy()
    },
    /** 跳转到流程设计页面 */
    handleUpdate(row){

      console.log("运行到这里了！！！");

      this.modelerStore.draftXml = null;
      this.$router.push({
        path: '/flowable/definition/model',
        query: {
          deployId: row.deploymentId,
          category: this.queryParams.category,
          formId: row.formId,
        }
      })
    },
    /** 流程图查看 */
    handleReadImage(deployId){
      this.readImage.title = "流程图";
      this.readImage.open = true;
      flowXmlAndNode({deployId:deployId}).then(res => {
        this.flowData = res.data;
      })
    },
    /** 表单查看 */
    handleForm(formId) {
      getForm(formId).then(res => {
        const { formName, formType, formContent } = res.data;
        this.formTitleConf = { formName, formType };
        this.formConfOpen = true;
        if (formType === 'route') {
          this.renderForm = false;
          this.formCompName = formContent;
          this.$nextTick(() => {
            this.$refs.vFormRef.setFormData({},true);
          })
        } else {
          this.renderForm = true;
          this.$nextTick(() => {
            this.$refs.vFormRef.setFormJson(JSON.parse(formContent));
            this.$nextTick(() => {
              this.$refs.vFormRef.disableForm();
            })
          })
        }
      })
    },
    /** 挂载表单弹框 */
    handleAddForm(){
      this.ListFormDeploy()
    },
    /** 表单列表 */
    ListFormDeploy(){
      listForm(this.formQueryParams).then(res =>{
        this.formList = res.rows;
        this.formTotal = res.total;
        this.formDeployOpen = true;
      })
    },
    /** 流程设计 */
    handleDesign(row){
      console.log("运行到这里了！！！");
      this.modelerStore.draftXml = null;
      this.formDeployOpen = false;
      this.$router.push({
        path: '/flowable/definition/model',
        query: {
          category: this.queryParams.category,
          formId: row.formId,
        }
      })
    },
    handleCurrentChange(data) {
      if (data) {
        const { formType, formContent } = data;
        if (formType === 'route') {
          this.renderForm = false;
          this.formCompName = formContent;
          this.$nextTick(() => {
            this.$refs.vFormCurrentRowRef.setFormData({},true);
          })
        } else {
          this.renderForm = true;
          this.$nextTick(() => {
            this.$refs.vFormCurrentRowRef.setFormJson(JSON.parse(formContent));
            this.$nextTick(() => {
              this.$refs.vFormCurrentRowRef.disableForm();
            })
          })
        }
      }
    },
    /** 挂起/激活流程 */
    handleUpdateSuspensionState(row){
      let state = 1;
      if (row.suspensionState === 1) {
        state = 2
      }
      const params = {
        deployId: row.deploymentId,
        state: state
      }
      updateState(params).then(res => {
        this.$modal.msgSuccess(res.msg);
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deploymentIds = row.deploymentId || this.ids;
      this.$confirm('是否确认删除流程定义编号为"' + deploymentIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delDeployment(deploymentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有流程定义数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportDeployment(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },

    // 打开草稿箱
    handleOpenDraft() {
      this.draftOpen = true;
      this.getDraftList();
    },

    // 获取草稿箱列表
    getDraftList() {
      this.draftLoading = true;
      listDraft(this.draftQueryParams).then(res => {
        this.flowDraftList = res.rows;
        this.draftTotal = res.total;
        this.draftLoading = false;
      })
    },

    // 使用草稿
    handleUseDraft(row) {
      this.draftOpen = false;
      this.modelerStore.draftXml = row.xml;
      this.$router.push({
        path: '/flowable/definition/model',
        query: {
          category: row.category,
          formId: row.formId,
          draftId: row.id,
        }
      })
    },

    // 删除草稿
    handleDeleteDraft(row) {
      this.$modal.confirm('是否确认删除编号为"' + row.id + '"的草稿？').then(function () {
        return delDraft(row.id);
      }).then(() => {
        this.getDraftList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>

<style>
.inner {
  display: inline-block;
  margin: 5px; /* 可选，设置标签之间的间距 */
}
</style>
